package org.springframework.boot.autoconfigure.web.servlet.error;

import org.springframework.boot.web.servlet.error.ErrorController;
import top.malaoshi.sprout.utils.ResponseUtils;
import top.malaoshi.util.DateTime;
import org.springframework.http.HttpStatus;
import top.malaoshi.web.utils.Ajax;
import top.malaoshi.webmvc.GlobalVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 是SpringBoot默认处理异常方式，在没有配置任何异常处理时，当访问controlle抛出异常时，就是使用该方式处理异常的
 *
 * 也是SpringBoot 兜底 的处理异常方式，当 静态资源不存在时、过滤器抛错，都可以使用该方式处理异常
 */
public class BasicErrorController implements ErrorController {
    @Override
    public Object error(HttpServletRequest request, HttpServletResponse response,Exception e) {

        HttpStatus status = getStatus(request);
        if(Ajax.isAjax(request)){
            try {
                Map map = new HashMap();
                map.put("timestamp", DateTime.now("yyyy-MM-dd HH:mm:ss.SSS"));
                map.put("status",status.value());
                map.put("error",status.getReasonPhrase());
                map.put("message",e.getMessage());
                map.put("path",request.getServletPath());
                ResponseUtils.sendJSON(response,status.value(), map);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }else{
            // 状态码
//            request.setAttribute("javax.servlet.error.status_code",status.value());
//            // 异常对应的Class类
//            request.setAttribute("javax.servlet.error.exception_type",e.getClass());
//            // 错误消息
//            request.setAttribute("javax.servlet.error.message",e.getMessage());
//            // 访问哪个 URL 报的错
//            request.setAttribute("javax.servlet.error.request_uri",request.getServletPath());
//            //异常类对象，=========关键，其他项可没有============
//            request.setAttribute("javax.servlet.error.exception",e);
//            //发出异常的servlet名字，不带包名
//            request.setAttribute("javax.servlet.error.servlet_name", DispatcherServlet.class.getSimpleName());


            String html = GlobalVariable.errorHtml.replace("${status}",status.value()+"");
            html = html.replace("${message}",e.getMessage());
            try {
                ResponseUtils.print(response,html);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        return null;
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode);
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
